const toString = Object.prototype.toString;

/**
 * 判断类型
 * @param val
 * @param type
 */
export const is = (val: unknown, type: string) => {
    return toString.call(val) === `[object ${type}]`;
};

/**
 * 判断是否非undefined
 * @param val
 */
export const isDef = <T = unknown>(val?: T): val is T => {
    return typeof val !== 'undefined';
};

/**
 * 判断是否undefined
 * @param val
 */
export const isUnDef = <T = unknown>(val?: T): val is undefined => {
    return !isDef(val);
};

/**
 * 判断是否是null
 * @param val
 */
export const isNull = (val: unknown): val is null => {
    return val === null;
};

/**
 * 判断是null或undefined
 * @param val
 */
export const isNullOrUnDef = (val: unknown): val is null | undefined => {
    return isUnDef(val) || isNull(val);
};

/**
 * 判断是否是对象
 * @param val
 */
export const isObject = <T = Record<any, any>>(val: unknown): val is T => {
    return val !== null && is(val, 'Object');
};

/**
 * 判断是否数组
 * @param value
 * @returns boolean
 */
export const isArray = <T>(value: T | T[]): value is Array<T> => {
    return value && Array.isArray(value)
}

/**
 * 判断是否是数字
 * @param val
 */
export const isNumber = (val: unknown): val is number => {
    return is(val, 'Number');
};

/**
 * 判断是否是字符串
 * @param val
 */
export const isString = (val: unknown): val is string => {
    return is(val, 'String');
};

/**
 * 判断是否是布尔值
 * @param val
 */
export const isBoolean = (val: unknown): val is boolean => {
    return is(val, 'Boolean');
};

/**
 * 判断是否是日期类型
 * @param val
 */
export const isDate = (val: unknown): val is Date => {
    return is(val, 'Date');
};

/**
 * 判断是否是正则
 * @param val
 */
export const isRegExp = (val: unknown): val is RegExp => {
    return is(val, 'RegExp');
};

/**
 * 判断是否是函数
 * @param val
 */
export const isFunction = (val: unknown): val is Function => {
    return typeof val === 'function';
};

/**
 * 判断是否为0
 * @param val
 */
export const isZero = (val: unknown): boolean => {
    return val === 0 || val === '0';
};

/**
 * 判断是否NaN
 * @param val
 */
export const isNaN = (val: unknown): boolean => {
    return Number.isNaN(val);
};

/**
 * 判断是否空字符串
 * @param val
 */
export const isEmptyString = (val: unknown): boolean => {
    return val === '';
};

/**
 * 是否外链
 * @param str
 */
export const isOutLink = (str: string): boolean => {
    return str.indexOf('http://') > -1 || str.indexOf('https://') > -1;
};

/**
 * 判空 包含 0，‘0’，‘’，false
 * @param value
 */
export const isEmpty = (value: unknown): value is undefined | null => {
    if (value && typeof value === 'object') {
        return Object.keys(value).length === 0;
    } else if (Array.isArray(value)) {
        return value.length === 0;
    }
    return !value;
};

/**
 * 判断非空
 * @param v
 */
export const isNotEmpty = <T = any>(v: T | undefined | null): v is T => !isEmpty(v);

/**
 * 判断是否是有效的日期
 * @param date
 */
export const isValidDate = (date: Date | unknown): date is Date => {
    return date instanceof Date && !isNaN(date.getTime());
};